#pragma once
#include <iostream>
#include <stdlib.h>
#include <strings.h>
#include <string>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "Logger.hpp"

static int defaultfd = -1;

class Server
{
public:
    Server(uint16_t port)
        : _fd(defaultfd), _port(port), _isrunning(false)
    {
    }
    void Init()
    {
        // 创建socket
        _fd = socket(AF_INET, SOCK_DGRAM, 0);
        if (_fd< 0)
        {
            LOG(LogLevel::FATAL) << "socket创建失败";
            exit(1);
        }
        LOG(LogLevel::INFO) << "socket创建成功"<<_fd;
        // bind
        // 1.bind地址类型 端口号 ip地址
        struct sockaddr_in local;
        bzero(&local, sizeof(local));
        local.sin_family = AF_INET;
        local.sin_port = htons(_port);
        local.sin_addr.s_addr = htonl(INADDR_ANY);
        // 2.bind
        int m = bind(_fd, (struct sockaddr *)&local, sizeof(local));
        if (m < 0)
        {
            LOG(LogLevel::FATAL) << "bind socket 失败";
            exit(2);
        }
        LOG(LogLevel::INFO) << "bind socket 成功" << _fd;
    }
    void Start()
    {
        _isrunning = true;
        while (_isrunning)
        {
            char buffer[1024];
            buffer[0] = 0;
            struct sockaddr_in peer;
            socklen_t len = sizeof(peer);
            // 读取数据
            int n = recvfrom(_fd, buffer, sizeof(buffer), 0, (struct sockaddr *)&peer, &len);
            if (n > 0)
            {
                uint16_t clientport = ntohs(peer.sin_port);
                std::string clientip = inet_ntoa(peer.sin_addr);
                buffer[n] = 0;
                LOG(LogLevel::INFO) << "[" << clientip << ":" << clientport << "]# " << buffer;
                std::string echo_string = "server echo:";
                echo_string += buffer;
                // 写数据
                int m = sendto(_fd, echo_string.c_str(),echo_string.size(),0,(struct sockaddr*)&peer,len);
            }
        }
        _isrunning=false;
    }

    void Stop()
    {
        _isrunning=false;
    }
    ~Server() {}

private:
    int _fd; // 文件描述符
    uint16_t _port;
    bool _isrunning;
};